from ldap3 import Server, Connection
from phone import phone_num

loginun = 'CN=Administrator,CN=Users,DC=kingworth,DC=com'
loginpw = 'C1sco123'
server = Server('ldaps://192.168.1.40:636', connect_timeout=5)
conn = Connection(server, loginun, loginpw, auto_bind=True)


def createUser(username, phone):
    userdn = 'CN=' + username + ',OU=testOU,DC=kingworth,DC=com'
    conn.add(userdn, attributes={
        'objectClass': ['organizationalPerson', 'person', 'top', 'user'],
        'sAMAccountName': username,
        'userPrincipalName': "{}@kingworth.com".format(username),
        'displayName': username,
        'mail': username + '@kingworth.com',  # optional
        'telephoneNumber': phone,
    })
    # 添加用户到组
    conn.extend.microsoft.add_members_to_groups(userdn, 'CN=TestUserGroup-01,OU=testOU,DC=kingworth,DC=com')
    # - must be done before enabling user you must connect with SSL to set the password
    conn.extend.microsoft.modify_password(userdn, 'Aa@123456')
    conn.modify(userdn, {'userAccountControl': [('MODIFY_REPLACE', 512)]})
    # c.modify(userdn, {'userAccountControl': [('MODIFY_REPLACE', 2)]})     # disable user


# search = conn.search(
#     search_base='CN=Users,DC=kingworth,DC=com',
#     search_filter='(objectClass=group)',
#     search_scope='SUBTREE',
#     attributes=['member']
# )

# for entry in conn.entries:
# print(entry.member.values)
if __name__ == '__main__':
    pass
    for num in range(102, 103):
        username = 'user' + str(num)
        createUser(username, phone_num(num))
        print('创建' + username)
